<template>
  <div>
    <h3>用户管理</h3>
    <el-table :data="cutObj.records" stripe>
      <el-table-column prop="name" label="用户名"></el-table-column>
      <el-table-column prop="pwd" label="密码"></el-table-column>
      <el-table-column prop="realName" label="真实姓名"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="danger" @click="remove(scope.row.id)">删除用户</el-button>
          <el-button type="primary" @click="showUpdateDialog(scope.row.id)">修改权限</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        background
        layout="prev, pager, next, jumper"
        :total="cutObj.total"
        @current-change="findByItem"
        style="margin-top: 20px"
    />


    <div style="margin-top: 50px;display: flex;width: 500px;justify-content: space-around">
      <el-button type="primary" @click="showAddDialog">添加新用户</el-button>
      <div>
        客户名称:
        <el-input style="width: 200px" v-model="paramObj.name"></el-input>
        <el-button type="primary" @click="findByItem(1)">查询</el-button>
      </div>
    </div>

    <el-dialog
        v-model="showAdd"
        title="添加用户"
        width="40%"
    >
      <el-form
          :model="addUserObj"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          status-icon
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addUserObj.userName" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="addUserObj.realName" style="width: 200px;"/>
        </el-form-item>

        <el-form-item label="拥有角色" prop="roleIdArr">
          <el-checkbox-group v-model="addUserObj.roleIdArr">
            <el-checkbox v-for="item in roleList" :label="item.id" :key="item.id" name="roleIdArr"
                         @change="showAddPermission">
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="拥有权限" style="height: 100px;">
          <span>{{ gradeStr }}</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addUser()">
            添加
          </el-button>
          <el-button @click="resetForm" style="margin-left: 50px">重置</el-button>
        </el-form-item>
      </el-form>
      <span style="color: red;margin-left: 100px">{{ errorAddInfo }}</span>
    </el-dialog>

    <!--    修改用户-->

    <el-dialog
        v-model="showUpdate"
        title="修改用户权限"
        width="40%"
    >
      <el-form
          :model="updateObj"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          status-icon
      >
        <el-form-item label="用户名">
          <span>{{ updateObj.name }}</span>
        </el-form-item>
        <el-form-item label="真实姓名">
          <span>{{ updateObj.realName }}</span>
        </el-form-item>

        <el-form-item label="当前角色">
          <el-checkbox-group v-model="updateRoleIdArr">
            <el-checkbox v-for="item in roleList" :label="item.id" name="roleIdArr"
                         @change="showUpdateGrade"
                         style="width: 85px">
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="拥有权限" style="height: 100px;">
          <span>{{ gradeStr }}</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateGrade">
            修改
          </el-button>
        </el-form-item>
      </el-form>

    </el-dialog>


  </div>
</template>
<script>
import axios from "axios";

export default {
  data() {
    return {
      pageSize: 3,
      currentPage: 1,
      cutObj: {},
      paramObj: {},


      //根据角色id查权限
      gradeIdArr: [],
      gradeStr: "",

      // 添加用户
      showAdd: false,
      errorAddInfo: "",
      addUserObj: {
        roleIdArr: []
      },
      roleList: [],
      rules: {
        userName: [
          {required: true, message: '用户名必须填写', trigger: 'blur'}
        ],
        realName: [
          {required: true, message: '真实姓名必须填写', trigger: 'blur'},
        ],
        roleIdArr: [
          {required: true, message: '必须选择一个角色', trigger: 'change'}
        ]
      },
      //修改用户权限
      showUpdate: false,
      updateObj: {},
      updateRoleIdArr: [],
    }
  },
  methods: {
    findByItem(pageNO) {
      this.currentPage = pageNO
      this.paramObj.pageNO = pageNO
      axios.get("/project/user/findByItem", {params: this.paramObj}).then(resp => {
        this.cutObj = resp.data
      })
    },
    showAddDialog() {
      this.showAdd = true;
      this.resetForm();
    },
    findRole() {
      axios.get("/project/role/findAll").then(
          resp => {
            this.roleList = resp.data;
          }
      )
    },
    showAddPermission() {
      this.gradeStr = "";
      let param = new URLSearchParams();
      param.append("roleIdArray", this.addUserObj.roleIdArr);
      axios.post("/project/permission/findByRoleIdArray", param).then(resp => {
        let gradeList = resp.data;
        let gradeArr = gradeList.map(n => n.name);
        this.gradeStr = gradeArr.join('、');
      })
    }
    ,
    addUser() {
      if (this.addUserObj.name != "" && this.addUserObj.realName != "" && this.addUserObj.roleIdArr.length != 0) {
        let formObj = new URLSearchParams();
        formObj.append("roleIdArray", this.addUserObj.roleIdArr);
        formObj.append("name", this.addUserObj.userName);
        formObj.append("realName", this.addUserObj.realName);

        axios.post("/project/user/add", formObj).then(resp => {
          if (resp.data == "ok") {
            this.showAdd = false;
            this.findByItem(1);
          } else {
            this.errorAddInfo = "用户名已存在，请重新输入";
          }
        })
      }
    },
    resetForm() {
      this.addUserObj = {roleIdArr: []};
      this.errorAddInfo = "";
    },
    remove(userId) {
      axios.get("/project/user/del", {params: {userId}}).then(resp => {
        if (resp.data == "ok") {
          this.findByItem(1);
        }else {
          alert("不能删除自己")
        }
      })
    },
    showUpdateDialog(userId) {
      this.showUpdate = true;
      axios.get("/project/user/findById", {params: {userId}}).then(resp => {
        this.updateObj = resp.data;
        this.updateRoleIdArr = resp.data.roleList.map(n => n.id);
        this.showUpdateGrade();
      })
    },
    showUpdateGrade() {
      this.gradeStr = "";
      let param = new URLSearchParams();
      param.append("roleIdArray", this.updateRoleIdArr);
      axios.post("/project/permission/findByRoleIdArray", param).then(resp => {
        let gradeList = resp.data;
        let gradeArr = gradeList.map(n => n.name);
        this.gradeStr = gradeArr.join('、');
      })
    },
    updateGrade() {
      let param = new URLSearchParams();
      param.append("userId", this.updateObj.id);
      param.append("newRoleArray", this.updateRoleIdArr);
      axios.post("/project/user/updateRole", param).then(resp => {
        if (resp.data == "ok") {
          this.showUpdate = false;
        }
      })
    }
  },
  created() {
    this.findByItem(1);
    this.findRole();
  }
}
</script>

<style scoped>

</style>